//
// Created by postgres on 5/8/17.
//
#include<stdio.h>
#include<stdlib.h>
#include "../include/common/stringx.h"

#define MAX_SIZE 20
typedef char ElemType;
typedef struct Snode  //结点结构
{
    ElemType data;
    int parent;
} PNode;

typedef struct  //树结构
{
    PNode tnode[MAX_SIZE];
    int n;                 //结点个数
} Ptree;

void InitPNode(Ptree *tree) {
    int i, j;
    char ch;
    //printf("请输入结点个数:\n");
    //scanf("%d",&(tree.n));
    (*tree).n = 10;
    char str[] = "0,a,-1;1,b,0;2,c,0;3,d,1;4,e,2;5,f,2;6,g,3;7,h,3;8,i,3;9,j,4";
    char delimiters1[] = ";";
    char delimiters2[] = ",";
    char *wrk, *rv1, *rv2;
    wrk = str;
    i = 0;
    while ((rv1 = str_split(&wrk, delimiters1))) {
        rv2 = str_split(&rv1, delimiters2);
        i = atoi(rv2);
        (*tree).tnode[i].data = *(str_split(&rv1, delimiters2));
        rv2 = str_split(&rv1, delimiters2);
        (*tree).tnode[i].parent = atoi(rv2);
    }

    //printf("请输入结点的序及值其双亲序号:\n");
    /* for(i=0; i<tree.n; i++)
     {
         fflush(stdin);
         scanf("%c,%d",&ch,&j);
         tree.tnode[i].data = ch;
         tree.tnode[i].parent = j;
     }*/
    (*tree).tnode[0].parent = -1;
}

//前序遍历
void PreOrder(Ptree tree, int num) {
    int i,j;
    for ( i= num; i <= tree.n; i++) {
        if (i == num) {
            printf(" %c 的父亲结点序号为 %d\n", tree.tnode[i].data, tree.tnode[i].parent);
            //cout<<"   "<<i<<"        "<<tree.node[i].data<<"        "<<tree.node[i].parent<<endl;
            for ( j = num + 1; j <= tree.n; j++) {
                if (tree.tnode[j].parent == i) {
                    PreOrder(tree, j);
                }
            }
        }
    }
}

void FindParent(Ptree *tree) {
    int i;
    printf("请输入要查询的结点的序号\n");
    scanf("%d", &i);
    printf(" %c 的父亲结点序号为 %d\n", (*tree).tnode[i].data, (*tree).tnode[i].parent);
}

void tree_parent_test() {
    Ptree tree;
    InitPNode(&tree);
    PreOrder(tree,0);
}
